import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-01-22
 * Time: 16:42
 */
public class MySingleList {
    class Node {
        //定于成内部类
        public int val; //存储的数据
        public Node next;//存储下一个节点的地址

        public Node(int val) {
            this.val = val;  //不给next,如果没存的话，不知道下一个节点的地址
        }
    }

    public Node head; //代表当前链表的头结点的引用


    //遍历链表
    public void display() {
        Node cur = head;
        //遍历完之后,就不知道链表的head的头结点了 head==null了
        while (cur != null) {  //不能head.next!=null最后一个结点打印不到
            System.out.print(cur.val + " ");
            cur = cur.next; //head往后走
        }
        System.out.println();
    }

    //递归逆序打印
    public void display1(Node head1) {
        if(head1 == null) {
            return;
        }
        if(head1.next == null) {
            System.out.print(head1.val + " ");
            return;
        }
        display1(head1.next);
        System.out.print(head1.val+" ");
    }

    //栈逆序打印
    public void display2() {
        Stack<Node> stack = new Stack<>();
        Node cur = head;
        while(cur != null) {
            stack.push(cur);
            cur = cur.next;
        }
        while(!stack.isEmpty()) {
            Node top = stack.pop();
            System.out.print(top.val+ " ");
        }
        System.out.println();
    }


    public void addLast(int data) {
        Node node = new Node(data);
        if (head == null) {
            head = node;
            return;
        }
        Node cur = head;
        while (cur.next != null) {
            cur = cur.next;
        }
        cur.next = node;

    }


    //得到单链表的长度
    public int size() {
        Node cur = head;
        int count = 0;
        while(cur != null) {
            count++;
            cur = cur.next;
        }
        return count;
    }

    //清空
    //链表中所有的节点都可以被回收
    public void clear() {
        head = null;
    }
}
